package com.caigou.component;

import com.caigou.bean.cms.entity.*;
import com.caigou.mapper.cms.*;
import com.caigou.pojo.ChannelDataList;
import com.caigou.pojo.HeaderConfig;
import com.caigou.service.ChannelService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 模板静态资源生成处理的工具类，处理所有的碎片
 */
@Component
@Slf4j
public class HtmlBuilderComponent {

    @Resource
    private TemplateComponent templateComponent;

    @Resource
    private ChannelService channelService;// 频道配置表service
    @Resource
    private FriendshipLinkMapper friendshipLinkMapper;// 友情链接service
    @Resource
    private LinkTypeMapper linkTypeMapper;// 友链
    @Resource
    private UsMapper usMapper;// 关于我们
    @Resource
    private ArticleMapper articleMapper;// 文章主表映射
    @Resource
    private ArticleKeywordMapper articleKeywordMapper;// 文章关键字表映射
    @Resource
    private FooterConfigMapper footerConfigMapper;//页脚配置

    @Value("${domain}")
    private String domain;
    @Value("${domainJunDui}")
    private String domainJunDui;
    @Value("${domainQiChe}")
    private String domainQiChe;
    @Value("${domainIT}")
    private String domainIT;
    @Value("${domainKongTiao}")
    private String domainKongTiao;
    @Value("${domainDianTi}")
    private String domainDianTi;
    @Value("${domainJiaJu}")
    private String domainJiaJu;

    @Value("${domainHuBei}")
    private String domainHuBei;
    @Value("${domainHeNan}")
    private String domainHeNan;
    @Value("${domainLiaoNing}")
    private String domainLiaoNing;
    @Value("${domainFuJian}")
    private String domainFuJian;
    @Value("${domainHaiNan}")
    private String domainHaiNan;
    @Value("${domainHeBei}")
    private String domainHeBei;// 河北
    @Value("${domainShanDong}")
    private String domainShanDong;// 山东
    @Value("${domainJiangSu}")
    private String domainJiangSu;// 江苏
    @Value("${domainShaanXi}")
    private String domainShaanXi;// 陕西
    @Value("${domainBeiJing}")
    private String domainBeiJing;// 北京
    @Value("${domainZheJiang}")
    private String domainZheJiang;// 浙江
    @Value("${domainYunNan}")
    private String domainYunNan;// 云南
    @Value("${domainGuiZhou}")
    private String domainGuiZhou;// 贵州
    @Value("${domainChongQing}")
    private String domainChongQing;// 重庆
    @Value("${domainTianJin}")
    private String domainTianJin;// 天津
    @Value("${domainShenZhen}")
    private String domainShenZhen;// 深圳
    @Value("${domainQingDao}")
    private String domainQingDao;// 青岛
    @Value("${domainDaLian}")
    private String domainDaLian;// 大连
    @Value("${domainXiZang}")
    private String domainXiZang;// 西藏
    @Value("${domainXinJiang}")
    private String domainXinJiang;// 新疆
    @Value("${domainNingXia}")
    private String domainNingXia;// 宁夏
    @Value("${domainGuangXi}")
    private String domainGuangXi;// 广西
    @Value("${domainNeiMengGu}")
    private String domainNeiMengGu;// 内蒙古
    @Value("${domainGanSu}")
    private String domainGanSu;// 甘肃
    @Value("${domainBingTuan}")
    private String domainBingTuan;// 新疆生产建设兵团

    // 关于我们、加入我们、联系我们
    public String buildUsHtml(Integer id){
        Us us = usMapper.selectByPrimaryKey(id);
        Map<String, Object> map = new HashMap<>();
        map.put("id", us.getId());
        map.put("usName", us.getUsName());
        map.put("usImage", us.getUsImage());
        map.put("usContent", us.getUsContent());
        String url = null;
        try {
            url = templateComponent.createHtml(us.getTemplateCode(), map);
        } catch (IOException e){
            log.error(e.getMessage(), e);
        }
        return url;
    }

    // 友情链接
    public String buildFriendshipLinkHtml(){
        List<LinkType> linkTypeList = linkTypeMapper.listLinkType(1);
        for(LinkType linkType:linkTypeList){
            List<FriendshipLink> friendshipLinks = friendshipLinkMapper.listFriendshipLinkByLinkTypeId(linkType.getId());
            linkType.setFriendshipLinkList(friendshipLinks);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("linkTypeList", linkTypeList);
        // 返回生成的url
        String url = null;
        try{
            url = templateComponent.createHtml("FRIENDSHIPLINK", map);
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }
        return url;
    }

    // 反侵权公告
    public String buildTortHtml(Copyright imageCopyright, Copyright announcementCopyright){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("domain",domain);
        map.put("tortImage", imageCopyright.getCopyrightValue());
        map.put("tortAnnouncement", announcementCopyright.getCopyrightValue());
        String tortUrl=null;
        try{
            // 同步更新公共碎片--反侵权公告跳转页面
            tortUrl = templateComponent.createHtml("PUBLICFRAGMENTTORT", map);
            // 更新反侵权公告底层页内容
            tortUrl = templateComponent.createHtml("TORT", map);
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }
        return tortUrl;
    }

    /** 碎片类型处理 **/
    // 频道头11个
    public String buildHeaderHtml(String plateId) {
        // 获取头文件信息
        HeaderConfig headerConfig = channelService.loadChannelHeaderConfig(plateId);// 获取头文件配置信息
        HeaderConfig phoneConfig = channelService.loadChannelHeaderConfig("100010601");// 获取全局手机二维码配置
        // 封装模板参数
        Map<String, Object> map = new HashMap<>();
        // 全站域名
        map.put("domain",domain);
        map.put("domainJunDui",domainJunDui);
        map.put("domainQiChe",domainQiChe);
        map.put("domainIT",domainIT);
        map.put("domainKongTiao",domainKongTiao);
        map.put("domainDianTi",domainDianTi);
        map.put("domainJiaJu",domainJiaJu);

        map.put("domainHuBei", domainHuBei);
        map.put("domainHeNan", domainHeNan);
        map.put("domainLiaoNing", domainLiaoNing);
        map.put("domainFuJian", domainFuJian);
        map.put("domainHaiNan", domainHaiNan);
        map.put("domainHeBei", domainHeBei);
        map.put("domainShanDong", domainShanDong);
        map.put("domainJiangSu", domainJiangSu);
        map.put("domainShaanXi", domainShaanXi);
        map.put("domainBeiJing", domainBeiJing);
        map.put("domainZheJiang", domainZheJiang);
        map.put("domainYunNan", domainYunNan);
        map.put("domainGuiZhou", domainGuiZhou);
        map.put("domainChongQing", domainChongQing);
        map.put("domainTianJin", domainTianJin);
        map.put("domainShenZhen", domainShenZhen);
        map.put("domainQingDao", domainQingDao);
        map.put("domainDaLian", domainDaLian);
        map.put("domainXiZang", domainXiZang);
        map.put("domainXinJiang", domainXinJiang);
        map.put("domainNingXia", domainNingXia);
        map.put("domainGuangXi", domainGuangXi);
        map.put("domainNeiMengGu", domainNeiMengGu);
        map.put("domainGanSu", domainGanSu);
        map.put("domainBingTuan", domainBingTuan);

        map.put("channelHomeUrl", headerConfig.getChannelHomeUrl());// 当前频道首页链接地址
        log.info("---plateId={}, channelHomeUrl={}, channelName={}", plateId, headerConfig.getChannelUrl(), headerConfig.getChannelName());
        map.put("channelLogo", headerConfig.getChannelLogo());// 频道log
        map.put("channelText", headerConfig.getChannelText());// 频道logAlt
        map.put("channelWeChatLogo", headerConfig.getChannelWeChatLogo());// 频道微信二维码
        map.put("channelWeChatText", headerConfig.getChannelWeChatText());// 频道微信展示文字
        map.put("siteLogo", phoneConfig.getSiteLogo());// 全局移动端手机二维码
        map.put("channelStatus", phoneConfig.getChannelStatus());// 全局移动端手机二维码状态
        map.put("channelDescription", phoneConfig.getChannelDescription());// 全局移动端手机二维码alt
        // 获取年会频道中集采年会、监管峰会的链接地址
        String annualMeetingPlateId = "100010401";//集采年会
        String summitMeetingPlateId = "100010402";//监管峰会
        List<ChannelDataList > annualList = channelService.loadChannelRecommendDataList(annualMeetingPlateId);
        List<ChannelDataList> summitList = channelService.loadChannelRecommendDataList(summitMeetingPlateId);
        if(annualList!=null&&annualList.size()>0){
            String articleId = annualList.get(0).getArticleId();
            Article article = articleMapper.loadArticle(articleId);
            String articleUrl = null;
            if(article.getArticleOutLinkStatus()==1){
                articleUrl = article.getArticleOutLink();
            }else{
                articleUrl = article.getArticleUrl();
            }
            map.put("annualMeetingUrl", articleUrl);
            log.info("annualMeetingPlateId={}, annualMeetingUrl={}", annualMeetingPlateId, articleUrl);
        }
        if(summitList!=null&&summitList.size()>0){
            String articleId = summitList.get(0).getArticleId();
            Article article = articleMapper.loadArticle(articleId);
            String articleUrl = null;
            if(article.getArticleOutLinkStatus()==1){
                articleUrl = article.getArticleOutLink();
            }else{
                articleUrl = article.getArticleUrl();
            }

            map.put("summitMeetingUrl", articleUrl);
            log.info("summitMeetingPlateId={}, summitMeetingUrl={}", summitMeetingPlateId, articleUrl);
        }
        // 返回生成的url
        String url = null;
        try {
            switch (plateId){
                case "101":// 首页头文件
                    url = templateComponent.createHtml("HEADER", map);
                    break;
                case "102":// 采购人频道
                    url = templateComponent.createHtml("PURCHASERHEADER", map);
                    break;
                case "103":// 采购实务频道
                    url = templateComponent.createHtml("PRACTICEHEADER", map);
                    break;
                case "104":// 监管频道
                    url = templateComponent.createHtml("SUPERVISEHEADER", map);
                    break;
                case "105":// 研究院频道
                    url = templateComponent.createHtml("ACADEMYHEADER", map);
                    break;
                case "106":// 军队频道
                    url = templateComponent.createHtml("ARMYHEADER", map);
                    break;
                case "107":// 汽车频道
                    url = templateComponent.createHtml("AUTOHEADER", map);
                    break;
                case "108":// IT频道
                    url = templateComponent.createHtml("ITHEADER", map);
                    break;
                case "109":// 电梯频道
                    url = templateComponent.createHtml("ELEVATORHEADER", map);
                    break;
                case "110":// 空调电器频道
                    url = templateComponent.createHtml("CONDITIONERHEADER", map);
                    break;
                case "111":// 家具频道
                    url = templateComponent.createHtml("FURNITUREHEADER", map);
                    break;
                case "201":// 河北
                    url = templateComponent.createHtml("HEBEIHEADER", map);
                    break;
                case "301":// 河南
                    url = templateComponent.createHtml("HENANHEADER", map);
                    break;
                case "401":// 山东
                    url = templateComponent.createHtml("SHANDONGHEADER", map);
                    break;
                case "601":// 辽宁
                    url = templateComponent.createHtml("LIAONINGHEADER", map);
                    break;
                case "901":// 江苏
                    url = templateComponent.createHtml("JIANGSUHEADER", map);
                    break;
                case "1001":// 江苏
                    url = templateComponent.createHtml("ZHEJIANGHEADER", map);
                    break;
                case "1201":// 福建
                    url = templateComponent.createHtml("FUJIANHEADER", map);
                    break;
                case "1401"://湖北分站
                    url = templateComponent.createHtml("HUBEIHEADER", map);
                    break;
                case "1701":// 海南
                    url = templateComponent.createHtml("HAINANHEADER", map);
                    break;
                case "1901":// 贵州
                    url = templateComponent.createHtml("GUIZHOUHEADER", map);
                    break;
                case "2001":// 云南
                    url = templateComponent.createHtml("YUNNANHEADER", map);
                    break;
                case "2101":// 陕西
                    url = templateComponent.createHtml("SHAANXIHEADER", map);
                    break;
                case "2401":// 北京
                    url = templateComponent.createHtml("BEIJINGHEADER", map);
                    break;
                case "2501":// 天津
                    url = templateComponent.createHtml("TIANJINHEADER", map);
                    break;
                case "2601":// 重庆
                    url = templateComponent.createHtml("CHONGQINGHEADER", map);
                    break;
                case "3801":// 深圳
                    url = templateComponent.createHtml("SHENZHENHEADER", map);
                    break;
                case "3501":// 青岛
                    url = templateComponent.createHtml("QINGDAOHEADER", map);
                    break;
                case "3401":// 大连
                    url = templateComponent.createHtml("DALIANHEADER", map);
                    break;
                case "3201":// 西藏
                    url = templateComponent.createHtml("XIZANGHEADER", map);
                    break;
                case "3101":// 新疆
                    url = templateComponent.createHtml("XINJIANGHEADER", map);
                    break;
                case "3001":// 宁夏
                    url = templateComponent.createHtml("NINGXIAHEADER", map);
                    break;
                case "2901":// 广西
                    url = templateComponent.createHtml("GUANGXIHEADER", map);
                    break;
                case "2801":// 内蒙古
                    url = templateComponent.createHtml("NEIMENGGUHEADER", map);
                    break;
                case "2201":// 甘肃
                    url = templateComponent.createHtml("GANSUHEADER", map);
                    break;
                case "3301":// 甘肃
                    url = templateComponent.createHtml("BINGTUANHEADER", map);
                    break;
            }
        } catch (IOException e){
            log.error(e.getMessage(),e);
        }
        return url;
    }

    // 频道尾1个
    public String buildFooterHtml() {
        //先生成footer碎片
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("domain", domain);
        //Page<?> page = PageHelper.startPage(1, 15);
        List<FriendshipLink> latestFriendshipLinks = friendshipLinkMapper.listFriendshipLink();
        HeaderConfig appConfig = channelService.loadChannelHeaderConfig("100011001");// 获取全局配置app下载二维码数据
        map.put("latestFriendshipLinks", latestFriendshipLinks);
        map.put("channelName", appConfig.getChannelName());
        map.put("siteLogo", appConfig.getSiteLogo());
        map.put("channelDescription", appConfig.getChannelDescription());

        //页脚logo图片及文字
        List<FooterConfig> footerTextList = footerConfigMapper.listFooterConfigByType(0);
        FooterConfig footerImage = footerConfigMapper.listFooterConfigByType(1).get(0);
        map.put("footerImage", footerImage);
        map.put("footerTextList", footerTextList);

        //获取分站列表
        List<String> channelValues = new ArrayList<>();
        channelValues.add("24");//北京BJ
        channelValues.add("26");//重庆CQ
//        channelValues.add("34");//大连DL
        channelValues.add("12");//福建FJ
        channelValues.add("22");//甘肃GS
        channelValues.add("29");//广西GX
        channelValues.add("19");//贵州GZ
        channelValues.add("2");//河北HB
        channelValues.add("14");//湖北HB
        channelValues.add("17");//海南HN
        channelValues.add("3");//河南HN
        channelValues.add("9");//江苏JS
        channelValues.add("6");//辽宁LN
        channelValues.add("28");//内蒙古NMG
        channelValues.add("30");//宁夏NX
        channelValues.add("35");//青岛QD
        channelValues.add("4");//山东SD
        channelValues.add("21");//陕西SX
        channelValues.add("38");//深圳SZ
        channelValues.add("25");//天津TZ
        channelValues.add("31");//新疆XJ
        channelValues.add("33");//新疆生产建设兵团XJ
        channelValues.add("32");//西藏XZ
        channelValues.add("20");//云南YN
        channelValues.add("10");//浙江ZJ
        List<Channel> substationList = channelService.listChannelByChannelValues(channelValues);
        map.put("substationList", substationList);
        // 返回生成的url
        String url = null;
        try{
            url = templateComponent.createHtml("FOOTER", map);
            url = templateComponent.createHtml("AUTOFOOTER", map);
            url = templateComponent.createHtml("ITFOOTER", map);
            url = templateComponent.createHtml("ELEVATORFOOTER", map);
            url = templateComponent.createHtml("FURNITUREFOOTER", map);
            url = templateComponent.createHtml("CONDITIONERFOOTER", map);
            url = templateComponent.createHtml("ARMYFOOTER", map);

            url = templateComponent.createHtml("BEIJINGFOOTER", map);
            url = templateComponent.createHtml("CHONGQINGFOOTER", map);
//            url = templateComponent.createHtml("DALIANFOOTER", map);
            url = templateComponent.createHtml("FUJIANFOOTER", map);
            url = templateComponent.createHtml("GANSUFOOTER", map);
            url = templateComponent.createHtml("GUANGXIFOOTER", map);
            url = templateComponent.createHtml("GUIZHOUFOOTER", map);
            url = templateComponent.createHtml("HEBEIFOOTER", map);
            url = templateComponent.createHtml("HUBEIFOOTER", map);
            url = templateComponent.createHtml("HAINANFOOTER", map);
            url = templateComponent.createHtml("HENANFOOTER", map);
            url = templateComponent.createHtml("JIANGSUFOOTER", map);
            url = templateComponent.createHtml("LIAONINGFOOTER", map);
            url = templateComponent.createHtml("NEIMENGGUFOOTER", map);
            url = templateComponent.createHtml("NINGXIAFOOTER", map);
            url = templateComponent.createHtml("QINGDAOFOOTER", map);
            url = templateComponent.createHtml("SHANDONGFOOTER", map);
            url = templateComponent.createHtml("SHAANXIFOOTER", map);
            url = templateComponent.createHtml("SHENZHENFOOTER", map);
            url = templateComponent.createHtml("TIANJINFOOTER", map);
            url = templateComponent.createHtml("XINJIANGFOOTER", map);
            url = templateComponent.createHtml("BINGTUANFOOTER", map);
            url = templateComponent.createHtml("XIZANGFOOTER", map);
            url = templateComponent.createHtml("YUNNANFOOTER", map);
            url = templateComponent.createHtml("ZHEJIANGFOOTER", map);
        }catch(IOException e){
            log.error(e.getMessage(),e);
        }
        return url;
    }

    // 版权声明
    public String buildCopyrightHtml(Copyright copyright){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("copyrightValue", copyright.getCopyrightValue());
        // 返回生成的url
        String url = null;
        try{
            url = templateComponent.createHtml("COPYRIGHT", map);
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }
        return url;
    }

    // 文章作者
    public String buildPromoterHtml(ArticlePromoter articlePromoter){
        //生成推荐作者html碎片
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("articlePromoterId", articlePromoter.getId());
        log.info("----------authorImage={}----------", articlePromoter.getAuthorImage());
        map.put("authorImage", articlePromoter.getAuthorImage());
        map.put("name", articlePromoter.getName());
        map.put("authorPost", articlePromoter.getAuthorPost());
        map.put("authorIntro", articlePromoter.getAuthorIntro());
        map.put("domain", domain);
        int articleCount = articleMapper.getArticleCountByArticlePromoter(articlePromoter.getId());
        map.put("articleCount", articleCount);
        List<Article> latestArticles = articleMapper.listLatestArticleByArticlePromoter(articlePromoter.getId());
        //构建关键词
        for(Article article:latestArticles){
            String keyword = article.getArticleKeyWord();
            if(keyword!=null&&keyword.length()>0){
                String[] strings = keyword.split(",");
                int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
                List<ArticleKeyword> articleKeywords = articleKeywordMapper.findArticleKeywordsByIds(array);
                article.setArticleKeywordList(articleKeywords);
            }
        }
        map.put("latestArticles", latestArticles);
        // 返回生成的url
        String url = null;
        try{
            url = templateComponent.createHtml("PROMOTER", map);
            log.info("生成作者id={}，姓名={}的碎片url={}",articlePromoter.getId(), articlePromoter.getName(), url);
        }catch(IOException ioe){
            log.error(ioe.getMessage(), ioe);
        }
        return url;
    }


    //政采榜频道首页政采榜介绍碎片
    public String buildGovProListIntro(List<GovProListIntroGroup> introGroupList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("introGroupList",introGroupList);
        String url = null;
        try{
            url = templateComponent.createHtml("GOVPROLISTINTRO", map);
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }
        return url;
    }

    //政采榜频道首页政采榜奖项碎片
    public String buildGovProListPrizeSum(List<GovProListPrizeSum> prizeSumList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("prizeSumList",prizeSumList);
        String url = null;
        try{
            url = templateComponent.createHtml("GOVPROLISTPRIZESUM", map);
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }
        return url;
    }


    //政采榜频道首页政采榜专家评委碎片
    public String buildGovProListExpert(List<GovProListExpert> expertList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("expertList",expertList);
        String url = null;
        try{
            url = templateComponent.createHtml("GOVPROLISTEXPERT", map);
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }
        return url;
    }


    public String buildGovProListGovList(List<GovProListPrizeYear> yearList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("yearList",yearList);
        String url = null;
        try{
            url = templateComponent.createHtml("GOVPROLISTGOVWINNER", map);
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }
        return url;
    }

    public String buildGovProListEnterpriseList(List<GovProListPrizeYear> yearList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("yearList",yearList);
        String url = null;
        try{
            url = templateComponent.createHtml("GOVPROLISTENTERPRISEWINNER", map);
        }catch(IOException e){
            log.error(e.getMessage(), e);
        }
        return url;
    }

    public String buildGovFooterHtml() {
        //先生成政采榜footer碎片
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("domain", domain);
        // 返回生成的url
        String url = null;
        try{
            url = templateComponent.createHtml("GOVPROLISTFOOTER", map);
        }catch(IOException e){
            log.error(e.getMessage(),e);
        }
        return url;
    }

    /**生成个人中心左侧碎片（个人头像、我的收藏、我的评论、我的消息、账户设置等内容的碎片）
     *
     * @return
     */
    public String buildPersonalAsideHtml(){
        //生成个人中心左侧碎片
        Map<String, Object> map = new HashMap<String, Object>();
        // 返回生成的url
        String url = null;
        try{
            url = templateComponent.createHtml("PERSONALASIDE", map);
        }catch(IOException e){
            log.error(e.getMessage(),e);
        }
        return url;
    }

    public String buildItemListHtml() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("domain", domain);

        // 返回生成的url
        String url = null;
        try{
            url = templateComponent.createHtml("ITEMLIST", map);
        }catch(IOException e){
            log.error(e.getMessage(),e);
        }
        return url;

    }
}
